package com.test.testopengl;


import java.io.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;

import javax.microedition.khronos.opengles.GL10;

import android.util.Log;

public class Arm 
{
	private int triangle_number=0;
	/** The ReadSTL sector */
	private Sector sector1;
	/** The buffer holding the vertices */
	private FloatBuffer vertexBuffer;
	/** The initial vertex definition */
	private float[] vertices;
	/** The buffer holding the normals */
	private FloatBuffer normalBuffer;
	/** The normal coordinates (u, v) */	
	private float[] normals;
	//**m_Triangle 鐨勫疄渚�
	private m_Triangle[] m_triangle;
	//**鐢ㄤ互娴嬭瘯
	private String str_line;
	
	@SuppressWarnings("null")
	
	
	public Arm(String path)throws IOException
	{
		ReadSTL(path);
		//
		ByteBuffer byteBuf = ByteBuffer.allocateDirect(vertices.length * 4);
		byteBuf.order(ByteOrder.nativeOrder());
		vertexBuffer = byteBuf.asFloatBuffer();
		vertexBuffer.put(vertices);
		vertexBuffer.position(0);
		
		//
		byteBuf = ByteBuffer.allocateDirect(normals.length * 4);
		byteBuf.order(ByteOrder.nativeOrder());
		normalBuffer = byteBuf.asFloatBuffer();
		normalBuffer.put(normals);
		normalBuffer.position(0);
		
		
	}
	
	public void draw(GL10 gl)
	{
		//******************************************************	
		//鏄剧ず椤剁偣鏁扮粍
		//Enable the vertex, texture and normal state
		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
	//	gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
		gl.glEnableClientState(GL10.GL_NORMAL_ARRAY);
		//Set the face rotation 璁剧疆閫嗘椂閽堟柟娉曚负闈㈢殑鈥滃墠闈⑩��
		gl.glFrontFace(GL10.GL_CCW);
		//鎵撳紑 蹇界暐鈥滃悗闈⑩�濊缃�
		gl.glEnable(GL10.GL_CULL_FACE);
//		鏄庣‘鎸囨槑鈥滃拷鐣モ�滃摢涓潰鐨勪唬鐮佸涓嬶細
		gl.glCullFace(GL10.GL_BACK);
		//Point to our buffers
		gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);	
		gl.glNormalPointer(GL10.GL_FLOAT, 0, normalBuffer);
		//Draw the vertices as triangles
		gl.glDrawArrays(GL10.GL_TRIANGLES, 0, vertices.length / 3);	
		//Disable the client state before leaving
		gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
	//	gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
		gl.glDisableClientState(GL10.GL_NORMAL_ARRAY);
//******************************************************

	}
	public boolean ReadSTL(String path) throws IOException
	{
		
//			//灏濊瘯鐢⊿tringTokenizer鏉ヨ鍙栨枃浠讹紝鐪嬩娇鐢ㄦ晥鐜囧浣�
			try {
//				//Some temporary variables
				sector1 = new Sector();
				
				List<String> lines = null;
				StringTokenizer tokenizer;
				
				//Quick Reader for the input file
				InputStream in=new FileInputStream(new File(path));  
				 
				InputStreamReader inreader=new InputStreamReader(in);
				BufferedReader reader = new BufferedReader(inreader);
//				BufferedReader reader = new BufferedReader(new FileReader(path));
				//Iterate over all lines
				String line = null;

//				//鑷繁瀹炵幇鏂囦欢璇诲彇
				sector1.numtriangles = this.GetNumber(path);
				sector1.triangle = new Triangle[sector1.numtriangles];
				lines = new ArrayList<String>();
				while((line=reader.readLine())!=null)
				{
					lines.add(line);				
				}			
//				//Clean up!
				reader.close();
										
				int count=0;
				for (int loop=0;loop<lines.size();loop++)
				{
					str_line=lines.get(loop);
					if(str_line.startsWith("  facet normal"))
					{
						Triangle triangle = new Triangle();
						tokenizer = new StringTokenizer(str_line);
						tokenizer.nextToken();tokenizer.nextToken();
						triangle.normal.x=Float.valueOf(tokenizer.nextToken());
						triangle.normal.y=Float.valueOf(tokenizer.nextToken());
						triangle.normal.z=Float.valueOf(tokenizer.nextToken());
						loop=loop+1;;
						for (int i=0;i<3;i++)
						{
							loop=loop+1;
							str_line=lines.get(loop);
							tokenizer = new StringTokenizer(str_line);
							tokenizer.nextToken();
							triangle.vertex[i].x=Float.valueOf(tokenizer.nextToken());
							triangle.vertex[i].y=Float.valueOf(tokenizer.nextToken());
							triangle.vertex[i].z=Float.valueOf(tokenizer.nextToken());							
						}
						count++;
						sector1.triangle[count-1]=triangle;
					}
			}
				
			//If anything should happen, write a log and return
			} catch(Exception e) {
				Log.e("World", "Could not load the World file!", e);
//				return e;
			}			
			vertices = new float[sector1.numtriangles * 3 * 3];
			normals = new float[sector1.numtriangles * 3*3];
			
			int vertCounter = 0;
			int norCounter = 0;

			for(Triangle triangle : sector1.triangle) {
				//
				for(Vertex vertex : triangle.vertex) {
					//
					vertices[vertCounter++] = vertex.x;
					vertices[vertCounter++] = vertex.y;
					vertices[vertCounter++] = vertex.z;
				}
				normals[norCounter++]=triangle.normal.x;
				normals[norCounter++]=triangle.normal.y;
				normals[norCounter++]=triangle.normal.z;
				normals[norCounter++]=triangle.normal.x;
				normals[norCounter++]=triangle.normal.y;
				normals[norCounter++]=triangle.normal.z;
				normals[norCounter++]=triangle.normal.x;
				normals[norCounter++]=triangle.normal.y;
				normals[norCounter++]=triangle.normal.z;
			}		
							
			str_line=sector1.triangle[sector1.numtriangles-1].vertex[2].z+"";
		
        return true;
        
//********************************************************	
//		Scanner sc=new Scanner(new File("/sdcard/stl.stl"));
//		String str = null;
//		int i=0;
//		float d;
//		m_triangle=new m_Triangle[this.GetNumber()];		
//        while(sc.hasNext())//杩樻湁鏁版嵁鍚楋紵
//        {
//        	if(sc.next().equals("normal"))
//        	{
//        		m_triangle[i]=new m_Triangle();
//        		m_triangle[i].normal.x=sc.nextDouble();
//        		m_triangle[i].normal.y=sc.nextDouble();
//        		m_triangle[i].normal.z=sc.nextDouble();
//        		sc.next();sc.next();
//        		for(int j=0;j<3;j++)
//        		{
//        			sc.next();
//        			m_triangle[i].vertex3D[j].x=sc.nextDouble();
//        			m_triangle[i].vertex3D[j].y=sc.nextDouble();
//        			m_triangle[i].vertex3D[j].z=sc.nextDouble();
//        		}
//        		i=i+1;
//        	}
//		}

		
		//鐢ˋrryaList鏁堢巼涔熶笉楂�
//		ArrayList<Float> Vertex=new ArrayList<Float>();		
//        while(sc.hasNext())//杩樻湁鏁版嵁鍚楋紵
//        {
//        	if(sc.next().equals("normal"))
//        	{
//        		Vertex.add(sc.nextFloat());
//        		Vertex.add(sc.nextFloat());
//        		Vertex.add(sc.nextFloat());
//        		sc.next();sc.next();
//        		for(int j=0;j<3;j++)
//        		{
//        			sc.next();
//        			Vertex.add(sc.nextFloat());
//        			Vertex.add(sc.nextFloat());
//        			Vertex.add(sc.nextFloat());
//        		}
//        		i=i+1;
//        	}
//		}
//        d=(Float)Vertex.get(Vertex.size()-1);
		
		
		//灏濊瘯鐢╢loat
//		float Vertex[]=new float[48];
//        while(sc.hasNext())//杩樻湁鏁版嵁鍚楋紵
//        {
//        	if(sc.next().equals("normal"))
//        	{
//        		Vertex[i++]=sc.nextFloat();
//        		Vertex[i++]=sc.nextFloat();
//        		Vertex[i++]=sc.nextFloat();
//        		sc.next();sc.next();
//        		for(int j=0;j<3;j++)
//        		{
//        			sc.next();
//        			Vertex[i++]=sc.nextFloat();
//        			Vertex[i++]=sc.nextFloat();
//        			Vertex[i++]=sc.nextFloat();
//        		}
//        	}
//		}	
//********************************************************		
	}
	
	
	/**
	 * A classic Vertex definition with
	 * texture coordinates.
	 */
	public class Vertex 
	{
		public float x, y, z;
	}
	
	public class Normal
	{
		public float x,y,z;
	}
	/**
	 * The Triangle class, containing
	 * all Vertices for the Triangle
	 */
	public class Triangle {
		//
		public Vertex[] vertex = new Vertex[3];
		public Normal normal=new Normal();
		public Triangle()
		{
			for(int i=0;i<3;i++)
			{
				vertex[i]=new Vertex();
			}
		}
	}

	/**
	 * The Sector class holding the number and
	 * all Triangles.
	 */
	public class Sector {
		//
		public int numtriangles;
		//
		public Triangle[] triangle;
	}
	
	public static int GetNumber(String path) throws IOException//鑾峰緱stl鏂囦欢涓笁瑙掑舰鐨勬暟閲�
	{
		String line;
		int Count = 0;
		InputStream in=TestOpenGLApplication.getInstance().getApplicationContext().getAssets().open("stl.stl");
		InputStreamReader inreader=new InputStreamReader(in);
		BufferedReader reader = new BufferedReader(inreader);
//		BufferedReader reader = new BufferedReader(new FileReader(path));
		while((line=reader.readLine())!=null)
		{
			Count++;				
		}
		reader.close();
		int i=(int)((Count-2)/7);
		return i;		
	}
}
